#include "NoteBookNavigationWindow.h"

namespace hps {
NoteBookNavigationWindow::NoteBookNavigationWindow() {
    m_noteBookChooser = new QComboBox();
    m_fileManager = new hps::FileManager();
    m_layout = new QVBoxLayout(this);
    m_label = new QLabel("笔记本");
    m_mode = new QStandardItemModel;
    m_fileManagerMenu = new QMenu();
    m_addFile = new QAction("新建文件");
    m_deleteFile = new QAction("删除文件");
    m_tempItem = nullptr;
    m_addDir = new QAction("新建目录");
    init();
    setUi();
    rspFunc();
}
void NoteBookNavigationWindow::init() {
    m_layout->setAlignment(Qt::AlignTop);
    m_layout->setContentsMargins(0, 0, 0, 0);
    m_layout->setSpacing(0);
    m_label->setAlignment(Qt::AlignCenter);
    m_fileManager->setHeaderHidden(true);
    loadStyle(m_noteBookChooser, "/home/hps/hps/Markdown-cpp/src/data/style/BookChooserStyle.qss");
}
void NoteBookNavigationWindow::setUi() {
    m_layout->insertWidget(0, m_label);
    m_noteBookChooser->setModel(getNoteBooks());
    m_layout->insertWidget(1, m_noteBookChooser);
    m_layout->insertWidget(2, m_fileManager);

    m_fileManagerMenu->addAction(m_addFile);
    m_fileManagerMenu ->addAction(m_addDir);
    m_fileManagerMenu->addAction(m_deleteFile);
}
QStandardItemModel *NoteBookNavigationWindow::getNoteBooks() {
    auto cfg = CONFIG()->getNoteBookCfg();
    for (auto &p: cfg.NoteBookMap) {
        QStandardItem *item = new QStandardItem(p.first.data());
        item->setIcon(QIcon("/home/hps/hps/Markdown-cpp/src/data/icon/bookChooser-book.svg"));
        // 添加项到模型中
        m_mode->appendRow(item);
    }
    return m_mode;
}
void NoteBookNavigationWindow::clickItem(int index) {
    std::string bookName = m_mode->item(index)->text().toStdString();
    m_mgrDir = CONFIG()->getNoteBookCfg().NoteBookMap[bookName];
    try {
        if (index == m_opBookId) return;
        m_fileManager->freeItems();
        m_fileManager->loadNoteBook(QString(m_mgrDir.c_str()), m_fileManager->invisibleRootItem());
    }
    catch (std::exception &e) {
        std::cerr << e.what() << std::endl;
    }
    m_opBookId = index;
}
void NoteBookNavigationWindow::rspFunc() {
    QObject::connect(m_noteBookChooser,
                     QOverload<int>::of(&QComboBox::activated),
                     this,
                     &NoteBookNavigationWindow::clickItem);
    QObject::connect(m_fileManager,
                     &FileManager::rightButtonClicked,
                     this,
                     &NoteBookNavigationWindow::showAndHandelFileManagerMenu);
    QObject::connect(m_addFile, &QAction::triggered, this, &NoteBookNavigationWindow::addFile);
    QObject::connect(m_deleteFile, &QAction::triggered, this, &NoteBookNavigationWindow::deleteFile);
    QObject::connect(m_addDir, &QAction::triggered, this, &NoteBookNavigationWindow::addDir);
}
void NoteBookNavigationWindow::flush() {
    m_fileManager->freeItems();
    m_fileManager->loadNoteBook(QString(m_mgrDir.c_str()), m_fileManager->invisibleRootItem());
    this->update();
}

bool checkFileType(QString str) {
    std::string s = str.toStdString();
    int index = s.find(".");
    int cnt = std::count(s.begin(), s.end(), '.');
    if (cnt > 1 || cnt == 0) {
        return false;
    }

    std::vector<char> cs = {'\\', '|', ':', ';', '\'', '\"', '<', '>', ',', '.', '?', '/'};
    if (index == 0) return false;
    for (int i = 0; i < (int) cs.size(); i ++) {
        if (s.find(cs[i]) != std::string::npos)
            return false;
    }
    return true;
}

void NoteBookNavigationWindow::showAndHandelFileManagerMenu(QTreeWidgetItem *_item) {
    m_tempItem = (TreeWidgetItem *) _item;
    QPoint globalMousePos = QCursor::pos();
    m_fileManagerMenu->exec(globalMousePos);
}
void NoteBookNavigationWindow::addFile() {
    if (m_tempItem == nullptr) {
        QMessageBox::critical(this, "Error", "m_tempItem is null.");
        return;
    }
    bool ok = false;
    std::string filePath = m_tempItem->getDirPath();
    QString fileName = QInputDialog::getText(nullptr, "输入文件名", "文件名",
                                             QLineEdit::Normal, QString(), &ok);
    if (ok) {
        if (fileName.isEmpty()) {
            QMessageBox::warning(this, "Warning", "文件名不能为空！");
        } else if (checkFileType(fileName)) {
            QMessageBox::warning(this, "Warning", "文件名的格式有问题");
        } else {
            if (filePath.back() != '/')
                filePath += "/";

            if (m_tempItem ->isDir()) {
                filePath += m_tempItem -> getItemName();
                if (filePath.back() != '/')
                    filePath += "/";
            }

            std::string cmd = "touch " + filePath + fileName.toStdString();
            int result = std::system(cmd.c_str());
            if (result != 0) {
                QMessageBox::critical(this, "Error", "创建文件失败!");
            }
            flush();
        }
    } else {
        QMessageBox::critical(this, "Error", "get file name error!");
    }
}
void NoteBookNavigationWindow::deleteFile() {
    if (m_tempItem == nullptr) {
        QMessageBox::critical(this, "Error", "m_tempItem is null.");
        return;
    }

    bool ans = QMessageBox::question(this, "提示", "是否删除文件/目录?", QMessageBox::Yes | QMessageBox::No);

    if (!ans) {
        return ;
    }

    std::string dirPath = m_tempItem -> getDirPath();
    if (dirPath.back() != '/')
        dirPath += "/";

    std::string cmd = "rm -r " + dirPath + m_tempItem ->text(0).toStdString();
    int result = std::system(cmd.c_str());
    if (result != 0) {
        QMessageBox::critical(this, "Error", "删除文件/目录失败!");
    }
    flush();
}
void NoteBookNavigationWindow::addDir() {
    if (m_tempItem == nullptr) {
        QMessageBox::critical(this, "Error", "m_tempItem is null.");
        return;
    }
    bool ok = false;
    std::string filePath = m_tempItem->getDirPath();
    QString dirName = QInputDialog::getText(nullptr, "输入目录名", "目录名",
                                             QLineEdit::Normal, QString(), &ok);
    if (ok) {
        if (dirName.isEmpty()) {
            QMessageBox::warning(this, "Warning", "目录不能为空！");
        } else {
            if (filePath.back() != '/')
                filePath += "/";

            // 如果点击的是一个空目录
            if (m_tempItem ->isDir()) {
                filePath += m_tempItem -> getItemName();
                if (filePath.back() != '/')
                    filePath += "/";
            }

            std::string cmd = "mkdir " + filePath + dirName.toStdString();
            int result = std::system(cmd.c_str());
            if (result != 0) {
                QMessageBox::critical(this, "Error", "创建目录失败!");
            }
            flush();
        }
    } else {
        QMessageBox::critical(this, "Error", "get file name error!");
    }
}
void NoteBookNavigationWindow::flushNoteBookChooser() {
    QStandardItemModel* model = (QStandardItemModel*) m_noteBookChooser -> model();
    model -> clear();

    m_noteBookChooser ->setModel(getNoteBooks());
    m_noteBookChooser -> update();
}

} // hps